var onDblClickRownumber = 0;  //双击次数判断  手机端双击会出现重复现象 以此来做一次判断
var perm01,perm02,perm03,perm04,perm05;  //权限字段
var audit;  //管理员权限字段
var openid;
var code = getQueryString("code");
let millName = '';

$(function () {
    setTimeout(function() {
        getUserInfoByCode();// 根据H5页面code请求后台用户信息，鉴定是否管理员
        setgrid();
        setgrid_detail();

        $('#win_detail').window({
            title:"用户权限明细",
            maximized:true,
            modal:true,
            collapsible:false,
            minimizable:false,
            closable:false,
            maximizable:false,
            resizable:false,
            closed:true
        });

        $('#win_QRcode').window({
            title:"新用户扫码关注",
            maximized:true,
            modal:true,
            collapsible:false,
            minimizable:false,
            closable:false,
            maximizable:false,
            resizable:false,
            closed:true
        });
    },20)
});


function setgrid() {
    $('#grid').datagrid({
        data: [],
        striped: true,
        autoSave: false,
        sortable: true,
        fit:true,
        fitColumns:true, //真正的自动展开/收缩列的大小，以适应网格的宽度，防止水平滚动
        rownumbers:true,
        remoteSort: false,
        singleSelect: true,
        showFooter: true,
        idField: 'iid',
        columns:[[
            {field:'iid',title:'主键',hidden:true},//width:100,
            {field:'sid',title:'客户',align:'center',width: '270'},
            {field:'usernumber',title:'用户数',align:'center',width: '100'},
            {field:'open_id',title:'用户数',align:'center',hidden:true},
        ]],
        onDblClickRow: function (Index,row) {//鼠标双击事件
            onDblClickRownumber=onDblClickRownumber+1;
            switchmill(row.sid);
        },
        rowStyler: function(index,row){
            if (row.open_id == openid){
                return 'color:#00DDDD;';
            }
        }
    });
}

function setgrid_detail() {
    $('#grid_detail').datagrid({
        data: [],
        striped: true,
        autoSave: false,
        sortable: true,
        fit:true,
        fitColumns:true, //真正的自动展开/收缩列的大小，以适应网格的宽度，防止水平滚动
        rownumbers:true,
        remoteSort: false,
        singleSelect: true,
        showFooter: true,
        idField: 'iid',
        columns:[[
            {field:'iid',title:'主键',width:100,hidden:true},
            {field:'real_name',title:'用户名',align:'center'},
            {field:'perm01',title:'修改',align:'center'},
            {field:'perm02',title:'备用2',align:'center'},
            {field:'perm03',title:'备用3',align:'center'},
            {field:'perm04',title:'备用4',align:'center'},
            {field:'perm05',title:'备用5',align:'center'},
        ]],
        onDblClickRow: function (Index,row) {//鼠标双击事件
        },
        onLoadSuccess:function(data) {
        }
    });
}

function getgrid() {
    $.ajax({
        url: getQueryForListCallProcUrl(),
        type: 'post',
        data: JSON.stringify(['usp_getadmindetail',openid]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let  data=cdata.data;
            $('#grid').datagrid('clearSelections');
            $('#grid').datagrid('loadData', data);
            $('.datagrid-header .datagrid-cell span ').css('font-size','16px');
        },
        complete: function (XMLHttpRequest, textStatus) {
        }
    })
}

// 获取指定客户下的所有微信用户
function getgrid_detail(mill) {
    $.ajax({
        url: getQueryForListCallProcUrl(),
        type: 'post',
        data: JSON.stringify(['usp_getmiluserdetail',mill]),
        contentType: "application/json;charset=UTF-8",
        success: function (cdata) {
            let  data=cdata.data;
            $('#grid_detail').datagrid('clearSelections');
            $('#grid_detail').datagrid('loadData', data);
            $('.datagrid-header .datagrid-cell span ').css('font-size','16px');
        },
        complete: function (XMLHttpRequest, textStatus) {
        }
    })
}


function switchmill(sid) {
if (onDblClickRownumber==1){
    $.messager.defaults = {ok: "确定", cancel: "取消", width: 300, closable: false};
    $.messager.confirm('确认', "是否确定更改到 "+sid, function (r) {
        if (r) {
            var str= "update user_mill set mill_sid='"+ sid + "' where open_id='"+openid+"'";
            $.ajax({
                url: getCUDUrl(),
                type: 'post',
                data: str,
                contentType: "application/json;charset=UTF-8",
                success: function (cdata) {
                    let  data=cdata.data;
                    getgrid();
                    onDblClickRownumber=0;
                },
                complete: function (XMLHttpRequest, textStatus) {
                }
            })
        }else{
            onDblClickRownumber=0;
        }
    });
}
}

// 查看明细
function openwin_detail() {
    var currentRow = $("#grid").datagrid("getSelected");//获得选中行的信息
    if (currentRow==null || currentRow==undefined) {
        alert('未选择中数据！');
        return;
    }else{
        $('#win_detail').window('open');
        millName = currentRow.sid;
        getgrid_detail(currentRow.sid);
    }
}

function openwin_QRcode() {
    var currentRow = $("#grid").datagrid("getSelected");//获得选中行的信息
    if (currentRow==null || currentRow==undefined) {
        alert('未选择中数据！');
        return;
    }else{
        document.getElementById('ewm').src="img/320.png";
        $('#win_QRcode').window('open');
        $("#sid").val(currentRow.sid);
        getQRcode(currentRow.sid)
    }
}

//获取二维码
function getQRcode(sid) {
    $.ajax({
        url : getQRCodeUrl(sid),
        type: 'get',
        dataType: 'json',
        success : function(cdata) {
            let data=cdata.data;
            document.getElementById('ewm').src=data;
        },
        error : function(e){
            console.log('请求获取二维码失败');
            alert('请求获取二维码失败');
        }
    })
}

// 删除选中的用户
function deleteUser(){
    const selectedRow = $("#grid_detail").datagrid("getSelected");//获得选中行的信息
    alert('选中行的数据');
    alert(JSON.stringify(selectedRow));
    if (selectedRow == null || selectedRow == undefined) {
        alert('选中一行数据后再进行本操作！');
        return;
    }

    const iid = selectedRow.iid;
    $.ajax({
        url : getDeleteUrl(iid),
        type: 'post',
        dataType: 'json',
        success : function(res) {
            alert('请求删除的响应结果是');
            alert(JSON.stringify(res));
            if(res.code !== 1){
                alert(res.msg);
                return
            }
            // 刷新表格
            alert('开始刷新表格' + millName);
            getgrid_detail(millName);
        },
        error : function(e){
            console.log(e);
            alert(e);
        }
    })
}

// 获取URL参数
function getQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]);
    return null;
}

// 根据H5页面code请求后台用户信息，鉴定是否管理员
function getUserInfoByCode() {
    const url = getUserInfoUrl(code);
    $.ajax({
        url: url,
        type: 'get',
        dataType: 'json',
        success: function (data) {
            if(data.code !== 1){
                window.location.href=`noauthorize.html?msg=${data.msg}`;
                return
            }
            const user = data.data;
            if(!user.audit) window.location.href='noauthorize.html?msg=没有权限访问该页面！';
            openid = user.openId;


            audit = user.audit;
            perm01 = user.perm01;
            if (audit){
                getgrid();
            }else {
                alert('无权限查看')
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log('失败回调');
        }
    })
}
